package com.cy.module;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cy.config.EnumConst;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.PackageInfo;
import com.cy.model.ProductLibrary;
import com.cy.model.ProductPackageMap;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerBind(controllerKey = "/clmp/packageInfo")
public class PackageInfoController extends WebApiController {
	@Override
	public void index() {
		PackageInfo packageInfo = getModel(PackageInfo.class);
		int page = getParaToInt("pageIndex");
		int pageSize = getParaToInt("limit");
		Page<PackageInfo> packageInfoPage = PackageInfo.dao.paginate(page,pageSize, PackageInfo.SELECT_ALL, packageInfo);
		renderBuiPage(packageInfoPage, 200);
	}

	@Override
	public void update() {
		int id = getParaToInt();
		PackageInfo tempPackageInfo = getModel(PackageInfo.class);
		PackageInfo packageInfo = PackageInfo.dao.findById(id);
		packageInfo.cover(tempPackageInfo);

		if (packageInfo.update()) {
			renderSuccess();
		} else {
			renderFail();
		}
	}

	@Override
	public void save() {
		PackageInfo packageInfo = getModel(PackageInfo.class);
		if (null == packageInfo || StringUtils.isEmpty(packageInfo.getPackTag())
				|| null == packageInfo.getNum()) {
			renderStatus(EnumConst.RetCode.PARAMETER_IS_NULL.getCode(), "参数不完整");
			return;
		}
		packageInfo.setCreateTime(new Date());
		if (packageInfo.save()) {
			renderSuccess();
		} else {
			renderFail();
		}
	}

	@Override
	public void delete() {
		String[] ids = getPara().split("-");
		for (String id : ids) {
			PackageInfo.dao.deleteById(id);
		}
		renderSuccess();
	}
	
	public void findProductList(){
		ProductLibrary productLibrary = getModel(ProductLibrary.class);
		productLibrary.setStatus(1);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Page<ProductLibrary> productLibraryPage = ProductLibrary.dao.pageProduct(page, pageSize, productLibrary);
        renderBuiPage(productLibraryPage, 200);
	}
	
	public void relationProduct() throws Exception{
		try{
			String idStr = getPara("ids");
			String packTag = getPara("packTag");
			String counts = getPara("counts");
			String[] countNums = counts.split(",");
			String[] ids = idStr.split(",");
			int count = 0;
			for (String id : ids) {
				ProductPackageMap packageMap = new ProductPackageMap();
				List<ProductPackageMap> results = packageMap.find("SELECT p_id FROM product_package_map WHERE product_id=? AND pack_tag= ?", id, packTag);
				
				packageMap.setProductId(Integer.parseInt(id));
				packageMap.setPackTag(packTag);
				packageMap.setProductCount(Integer.parseInt(countNums[count]));
				packageMap.setCreateTime(new Date());
				if (results.size() < 1) {
					packageMap.save();
				} else {
					packageMap.setPId(results.get(0).getPId());
					packageMap.update();
				}
				count++;
			}
			renderSuccess();
		}catch(Exception e){
			renderFail();
			throw new Exception(e);
		}
	}
	
	public void findPackageDetail() throws Exception{
		try{
			String packTag = getPara("packTag").trim();
			
			List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
			List<ProductPackageMap> productPackageMaps = ProductPackageMap.dao.find("SELECT p_id, product_id, pack_tag, product_count FROM product_package_map WHERE pack_tag = ?", packTag);
			
			for (ProductPackageMap packageMap : productPackageMaps) {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				ProductLibrary productLibrary = ProductLibrary.dao.findById(packageMap.getProductId());
				resultMap.put("p_id", packageMap.getPId());
				resultMap.put("product_id", packageMap.getProductId());
				resultMap.put("product_count", packageMap.getProductCount());
				resultMap.put("name", productLibrary.getName());
				resultMap.put("title", productLibrary.getTitle());
				resultMap.put("product_num", productLibrary.getProductNum());
				dataList.add(resultMap);
			}
			
			 JSONObject dataObj = new JSONObject();
			 JSONArray result = JSON.parseArray(JsonKit.listToJson(dataList, 5));
			 dataObj.put("rows", result);
			renderJson(dataObj);
		}catch(Exception e){
			throw new Exception(e);
		}
	}
	
	public void removeProduct() throws Exception{
		try {
			String[] ids = getPara("ids").split(",");
			for(String id : ids){
				ProductPackageMap.dao.deleteById(id);
			}
			renderSuccess();
		} catch (Exception e) {
			renderFail();
			throw new Exception(e);
		}
	}
	
	public void updateCounts() throws Exception {
		try {
			String[] counts = getPara("counts").split(",");
			String[] ids = getPara("ids").split(",");
			int count = 0;
			for (String id : ids) {
				ProductPackageMap packageMap = new ProductPackageMap();
				packageMap.setPId(Integer.parseInt(id));
				packageMap.setProductCount(Integer.parseInt(counts[count]));
				packageMap.update();
				count++;
			}
			renderSuccess();
		} catch (Exception e) {
			renderFail();
			throw new Exception(e);
		}
	}
}
